package com.cn.jdia.springmvc.handlers;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.google.gson.Gson;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Controller
public class ModifyController {

	@RequestMapping("/attencehistory")
	public String insertPeccancy(String start, HttpServletResponse response) throws IOException {
		System.out.println(" Get Attence History...");
		System.out.println("start:" + start);

		List<String> deptList = new ArrayList<String>();
		deptList.add("1号值班领导");
		deptList.add("2号总值班长");
		deptList.add("运行指挥中心");
		deptList.add("安质部运标部");
		deptList.add("公安分局");
		deptList.add("安保公司");
		deptList.add("机务维修公司");
		deptList.add("商务发展公司");
		deptList.add("地服公司");
		deptList.add("物流公司");
		deptList.add("急救中心");
		deptList.add("飞行区管理部");
		deptList.add("航站楼管理部");
		deptList.add("信息管理部");
		deptList.add("动力能源公司");
		deptList.add("工程部");
		deptList.add("汽运公司");
		deptList.add("停车场公司");
		deptList.add("实业公司");
		deptList.add("凯亚公司");
		deptList.add("商贸管理公司");

		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();

		ClassPathXmlApplicationContext w_context = new ClassPathXmlApplicationContext("springmvc.xml");
		DataSource ds = (DataSource) w_context.getBean("dataSource");

		JSONArray jsonData = new JSONArray();
		int count = 0;

		try {
			Connection conn = ds.getConnection();
			Statement st = conn.createStatement();

			for (int i = 0; i < deptList.size(); i++) {
				String PersonName0 = "";
				String PersonName1 = "";
				String CheckId0 = "";
				String CheckId1 = "";
				String PersonId0 = "";
				String PersonId1 = "";

				StringBuffer sb = new StringBuffer("select person_name,check_id,person_id,turnover from")
						.append(" jan_attence where check_date='").append(start.replaceAll("-", ""))
						.append("' and person_dept='").append(deptList.get(i)).append("' ")
						.append(" order by person_dept");
				// System.out.println(sb.toString());
				ResultSet rs = st.executeQuery(sb.toString());

				JSONObject jo = new JSONObject();
				jo.put("DeptId", i + 1 + "");
				jo.put("Dept", deptList.get(i));

				jo.put("PersonName0", "");
				jo.put("PersonName1", "");

				while (rs.next()) {
					int turnover = rs.getInt("turnover");
					if (turnover == 1) {
						PersonName1 = rs.getString("person_name");
						CheckId1 = rs.getString("check_id");
						PersonId1 = rs.getString("person_id");

						jo.put("PersonName1", PersonName1);
						jo.put("CheckId1", CheckId1);
						jo.put("PersonId1", PersonId1);
					} else if (turnover == 0) {
						PersonName0 = rs.getString("person_name");
						CheckId0 = rs.getString("check_id");
						PersonId0 = rs.getString("person_id");

						jo.put("PersonName0", PersonName0);
						jo.put("CheckId0", CheckId0);
						jo.put("PersonId0", PersonId0);
					}
				}
				jsonData.add(jo);
				count++;
			}

			st.close();
			conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}

		JSONObject jsonObject = new JSONObject();
		jsonObject.put("rows", jsonData);// JSONArray
		jsonObject.put("total", count);// 总记录数

		// System.out.println(jsonObject.toString());
		out.write(jsonObject.toString());
		out.flush();
		out.close();

		return null;
	}

	@RequestMapping("/modifyattence")
	public String modifyAttence(HttpServletRequest request, HttpServletResponse response) throws IOException {
		System.out.println("update pec info");

		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();

		// 改动后整行数据
		String json = request.getParameter("strJson");

		// 改动域
		String filed = request.getParameter("filed");

		// 改动前的值
		String oldValue = request.getParameter("oldValue");

		// date
		String date = request.getParameter("date").replaceAll("-", "");

		// System.out.println("数据:"+json+"---");
		System.out.println("日期:" + date);
		System.out.println("改动域:" + filed + "---");
		System.out.println("旧值:" + oldValue + "---");

		Gson gson = new Gson();
		@SuppressWarnings("unchecked")
		Map<String, String> map = gson.fromJson(json, HashMap.class);
		// System.out.println(map);

		String checkId0 = map.get("CheckId0");
		String checkId1 = map.get("CheckId1");

		String dept = map.get("Dept");

		String personId0 = map.get("PersonId0");
		String personId1 = map.get("PersonId1");

		String personName0 = map.get("PersonName0");
		String personName1 = map.get("PersonName1");

		System.out.println("交班ID:" + checkId0);
		System.out.println("接班ID:" + checkId1);
		System.out.println("部门:" + dept);
		System.out.println("交班身份证:" + personId0);
		System.out.println("接班身份证:" + personId1);
		System.out.println("交班人名:" + personName0);
		System.out.println("接班人名:" + personName1);

		ClassPathXmlApplicationContext w_context = new ClassPathXmlApplicationContext("springmvc.xml");
		DataSource ds = (DataSource) w_context.getBean("dataSource");

		int ret = -1;
		try {
			Connection conn = ds.getConnection();
			Statement st = conn.createStatement();

			if (oldValue == "") {
				System.out.println("此字段修改前为空");

				String idsql = "select max(check_id) max from jan_attence";
				ResultSet idRs = st.executeQuery(idsql);
				String id = "";
				while (idRs.next()) {
					id = idRs.getString("max");
				}
				System.out.println("id:" + id);
				int pkid = Integer.parseInt(id);
				pkid++;

				idRs.close();
				System.out.println("new Id:" + pkid);

				String tmpName = "";
				int turnover = -1;
				if (filed.equals("PersonName0")) {
					tmpName = personName0;
					turnover = 0;
				} else if (filed.equals("PersonName1")) {
					tmpName = personName1;
					turnover = 1;
				}

				String person_id = "";
				String idqry = "select identity_id from jan_person_cast where name='" + tmpName + "' and dept_name='"
						+ dept + "'";
				System.out.println(idqry);

				ResultSet idRs2 = st.executeQuery(idqry);
				while (idRs2.next()) {
					person_id = idRs2.getString("identity_id");
				}
				System.out.println("新ID:" + person_id);

				idRs2.close();

				if ((person_id.equals("")) || (person_id == null)) {

				} else {
					StringBuffer sb = new StringBuffer("insert into jan_attence values('").append(tmpName).append("','")
							.append(date).append("','','").append(dept).append("','12:00:00',true,'").append(pkid)
							.append("','").append(person_id).append("',").append(turnover).append(")");

					System.out.println(sb.toString());
					ret = st.executeUpdate(sb.toString());
				}

			} else {
				String tmpName = "";
				String tmpId = "";
				if (filed.equals("PersonName0")) {
					tmpName = personName0;
					tmpId = checkId0;
				} else if (filed.equals("PersonName1")) {
					tmpName = personName1;
					tmpId = checkId1;
				}

				StringBuffer sb = new StringBuffer("update jan_attence set person_name='");
				sb.append(tmpName);

				sb.append("',person_id=(select identity_id from jan_person_cast where name='").append(tmpName)
						.append("' and dept_name='").append(dept).append("') where check_id='").append(tmpId)
						.append("'");

				System.out.println(sb.toString());
				ret = st.executeUpdate(sb.toString());

				System.out.println("Ret:" + ret);
			}
			st.close();
			conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			out.write(ret + "");
		}

		out.flush();
		out.close();

		return null;
	}

}
